package io.renren.modules.sys.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.renren.common.utils.*;
import io.renren.modules.sys.config.SysBottomConfig;
import io.renren.modules.sys.entity.*;
import io.renren.modules.sys.service.SysBottomService;
import io.renren.modules.sys.service.SysBottomUserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 用户投注表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-11-08 19:36:41
 */
@RestController
@RequestMapping("/sys/sysbottomuser")
public class SysBottomUserController extends AbstractController{

	@Autowired
	private SysBottomUserService sysBottomUserService;

	@Autowired
	private SysBottomService sysBottomService;

	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:sysbottomuser:list")
	public R list(@RequestParam Map<String, Object> params){

		if (getUserId() != Constant.SUPER_ADMIN && hasRole((long)Constant.NORMAL_USER)) {
			params.put("userId", getUserId());
		}
		initParamTime(params);

		//查询列表数据
        Query query = new Query(params);

		List<SysBottomUserEntity> sysBottomUserList = sysBottomUserService.queryList(query);
		List<Map<String, Object>> list = Lists.newArrayListWithCapacity(sysBottomUserList.size());
		for (SysBottomUserEntity sysBottomUserEntity : sysBottomUserList) {
			Map<String, Object> map = ObjectUtils.objectToMap(sysBottomUserEntity);
			list.add(map);
		}
		if (CollectionUtils.isNotEmpty(sysBottomUserList)) {
			list.add(createTotalMap(params));
		}

		int total = sysBottomUserService.queryTotal(query);

		PageUtils pageUtil = new PageUtils(list, total, query.getLimit(), query.getPage());

		return R.ok().put("page", pageUtil);
	}

	private void initParamTime(Map<String, Object> params) {
		if (!params.containsKey("time")) {
			return;
		}
		if (StringUtils.equals("today", params.get("time").toString())) {
			params.put("startTime", DateUtils.format(new Date()));
			params.put("endTime", DateUtils.format(new Date()));
		}
	}

	/**
	 * 查询每日统计
	 */
	@RequestMapping("/querySumList")
	public R querySumListByDay(@RequestParam Map<String, Object> params) {

		if (getUserId() != Constant.SUPER_ADMIN && hasRole((long)Constant.NORMAL_USER)) {
			params.put("userId", getUserId());
		}
		//查询列表数据
		Query query = new Query(params);

		List<SysBottomTotalEntity> sumList = sysBottomUserService.querySumList(params);

		PageUtils pageUtil = new PageUtils(sumList, sumList.size(), query.getLimit(), query.getPage());

		return R.ok().put("page", pageUtil);
	}

	private Map<String, Object> createTotalMap(Map<String, Object> params) {
		SysBottomUserEntity amountTotal = sysBottomUserService.querAmountTotal(params);

		Map<String, Object> result = Maps.newHashMapWithExpectedSize(1);
		result.put("odds", "总计");
		result.put("amount", amountTotal.getAmount());
		result.put("winAmount", amountTotal.getWinAmount());
		return result;
	}

	/**
	 * 信息
	 */
	@RequestMapping("/info/{bottomId}")
	@RequiresPermissions("sys:sysbottomuser:info")
	public R info(@PathVariable("bottomId") Long bottomId){
		SysBottomUserEntity sysBottomUser = sysBottomUserService.queryObject(bottomId);

		return R.ok().put("sysBottomUser", sysBottomUser);
	}

	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@RequiresPermissions("sys:sysbottomuser:save")
	public R save(@RequestBody SysBottomUserEntity sysBottomUser){
		sysBottomUserService.save(sysBottomUser);

		return R.ok();
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("sys:sysbottomuser:update")
	public R update(@RequestBody SysBottomUserEntity sysBottomUser){
		sysBottomUserService.update(sysBottomUser);

		return R.ok();
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("sys:sysbottomuser:delete")
	public R delete(@RequestBody Long[] bottomIds){
		sysBottomUserService.deleteBatch(bottomIds);

		return R.ok();
	}

	/**
     * 下注
     */
    @RequestMapping("bottom")
    public R bottom(@RequestBody List<SysOddsCatetoryEntity> bottomList, Long bottomId) {

		if (bottomId == null) {
			return R.error("该局暂时无法下注，请刷新重试！");
		}
		SysBottomEntity sysBottomEntity = sysBottomService.queryCurrent();
		if (sysBottomEntity == null) {
			return R.error("下注尚未开启，请耐心等待！");
		}

		if (!sysBottomEntity.getBottomId().equals(bottomId)) {
			return R.error("该期已结束，请刷新重新选择");
		}
		Calendar endTime = Calendar.getInstance();
		endTime.setTime(sysBottomEntity.getCreateTime());
		endTime.add(Calendar.MINUTE, sysBottomEntity.getDuration() - SysBottomConfig.BOTTOM_END_TIME);

		if (endTime.getTime().before(new Date())) {
			return R.error("该期已封盘，请重新选择");
		}

		if (!hasEnoughMoney(bottomList)) {
			return R.error("对不起，您的余额不足，请先充值");
		}

		sysBottomUserService.bottom(bottomList, sysBottomEntity);

		return R.ok();
    }

    private boolean hasEnoughMoney(List<SysOddsCatetoryEntity> bottomList) {

    	Integer useMoney = 0;
		for (SysOddsCatetoryEntity sysOddsCatetoryEntity : bottomList) {
			for (SysOddsEntity sysOddsEntity : sysOddsCatetoryEntity.getList()) {
				useMoney += sysOddsEntity.getMoney();
			}
		}
		return getUser().getBalance() >= useMoney * 100;
	}
}
